<template>
  <div class="mpd-array-table padding-xs">
    <a-button @click="showModalHandle(true)" block>点击配置</a-button>
    <a-modal
      width="80%"
      title="属性配置"
      :visible="visible"
      @ok="showModalHandle(false)"
      @cancel="showModalHandle(false)"
      size="small"
    >
      <a-button class="margin-b-xs" @click="addRowData">添加行</a-button>
      <a-table bordered :columns="targetColumns" :data-source="data" size="small">
        <template v-for="(col, colIndex) in columns" :slot="col.dataIndex + 'Slot'" slot-scope="text, row, index">
          <a-input :value="text" :key="colIndex" @change="e => handleChange(e.target.value, row, col, index)" />
        </template>
        <template slot="operation" slot-scope="text, row, index">
          <a-button type="danger" @click="deleteRowData(index)">删除</a-button>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import configMixin from './config-mixin'

export default {
  name: 'MpdArrayTable',
  mixins: [configMixin],
  props: {
    columns: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      visible: false,
      defaultColumns: [
        {
          title: '操作',
          fixed: 'right',
          width: 100,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: []
    }
  },
  computed: {
    targetColumns() {
      return this.columns.concat(this.defaultColumns)
    }
  },
  methods: {
    showModalHandle(flag) {
      this.visible = flag
    },
    addRowData() {
      const tmp = {}
      this.columns.forEach(element => {
        tmp[element.dataIndex] = undefined
      })
      this.data.push(tmp)
    },
    deleteRowData(index) {
      this.data.splice(index, 1)
    },
    handleChange(value, row, col, index) {
      console.log(value, row, col, index)
      this.$set(this.data[index], col.dataIndex, value)
    }
  }
}
</script>
